package com.jeeplus.mob.common;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.jeeplus.mob.entity.AccessToken;
import com.jeeplus.mob.entity.JsTicket;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;


import net.sf.json.JSONObject;

public class WxUtil {


    private static final long MAX_TIME = 7200 * 1000;
    public static String APPID = "wxf659491d9b5b4282";
    public static String APPSECRET = "fc0b14730b1c42a44e3f1c7931a49bf5";
    private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";

    public static JSONObject doGetStr(String urlStr) throws ClientProtocolException, IOException, URISyntaxException {
        JSONObject jsonObject = null;
        // 创建默认的客户端实例
        CloseableHttpClient client = HttpClients.createDefault();
        // 创建get请求实例

        URL url = new URL(urlStr);
        URI uri = new URI(url.getProtocol(), url.getHost(), url.getPath(), url.getQuery(), null);
        HttpGet httpGet = new HttpGet(uri);
        // 客户端执行get请求 返回响应实体
        HttpResponse response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            String result = EntityUtils.toString(entity, "UTF-8");
            jsonObject = JSONObject.fromObject(result);
        }
        client.close();

        return jsonObject;
    }

    public static String doPost(String Url, String json) {
        String message = "";
        System.out.println(json);
        try {
            URL url = new URL(Url);
            HttpURLConnection http = (HttpURLConnection) url.openConnection();
            http.setRequestMethod("POST");
            http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);
            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
            System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
            http.connect();
            OutputStream os = http.getOutputStream();
            os.write(json.getBytes("UTF-8"));// 传入参数
            os.flush();
            os.close();
            InputStream is = http.getInputStream();
            int size = is.available();
            byte[] jsonBytes = new byte[size];
            is.read(jsonBytes);
            message = new String(jsonBytes, "UTF-8");
            System.out.println(message);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return message;
    }

    public static AccessToken getAccessToken() throws ClientProtocolException, IOException, URISyntaxException {
        AccessToken token = new AccessToken();
        String url = ACCESS_TOKEN_URL.replace("APPID", APPID).replace("APPSECRET", APPSECRET);// 将URL中的两个参数替换掉
        JSONObject jsonObject = doGetStr(url);// 使用刚刚写的doGet方法接收结果
        if (jsonObject != null) { // 如果返回不为空，将返回结果封装进AccessToken实体类
            token.setToken(jsonObject.getString("access_token"));// 取出access_token
            token.setExpiresIn(jsonObject.getString("expires_in"));// 取出access_token的有效期
        }
        return token;
    }

    public static String getSavedAccess_token() throws Exception {
        String mAccessToken = null;
//		File file = new File("F:/token.propertis");
        File file = new File("Mytoken.propertis");
        if (!file.exists()) {
            file.createNewFile();
        }
        if (file.length() == 0) {
            mAccessToken = getAccessToken().getToken();
            FileOutputStream fos = new FileOutputStream(file, false);
            AccessToken at = new AccessToken();
            at.setToken(mAccessToken);
            at.setExpiresIn(System.currentTimeMillis() + "");
            JSONObject json = JSONObject.fromObject(at);
            String obj = json.toString();
            fos.write(obj.getBytes());
            fos.close();
        } else {
            FileInputStream fis = new FileInputStream(file);
            byte[] b = new byte[2048];
            int len = fis.read(b);
            String mJsonAccess_token = new String(b, 0, len);// 读取到的文件内容
            JSONObject object = new JSONObject().fromObject(mJsonAccess_token);
            AccessToken access_token = (AccessToken) JSONObject.toBean(object, AccessToken.class);
            if (access_token.getExpiresIn() != null) {
                long saveTime = Long.parseLong(access_token.getExpiresIn());
                long nowTime = System.currentTimeMillis();
                long remianTime = nowTime - saveTime;
                // System.out.println(TAG + "时间差：" + remianTime);
                if (remianTime < MAX_TIME) {
                    JSONObject o = new JSONObject().fromObject(mJsonAccess_token);
                    AccessToken at = (AccessToken) JSONObject.toBean(o, AccessToken.class);
                    mAccessToken = at.getToken();
                } else {
                    mAccessToken = getAccessToken().getToken();
                    FileOutputStream fos = new FileOutputStream(file, false);// 不允许追加
                    AccessToken at = new AccessToken();
                    at.setToken(mAccessToken);
                    at.setExpiresIn(System.currentTimeMillis() + "");
                    JSONObject json = JSONObject.fromObject(at);
                    String obj = json.toString();
                    fos.write((obj).getBytes());
                    fos.close();
                }

            }

        }
        return mAccessToken;
    }

    public static String getSavedJsTicket() throws Exception {
        String mJsTicket = null;
        File file = new File("MyJsTicket.propertis");
        if (!file.exists()) {
            file.createNewFile();
        }
        if (file.length() == 0) {
            mJsTicket = getJsTicket().getTicket();
            FileOutputStream fos = new FileOutputStream(file, false);
            JsTicket jt = new JsTicket();
            jt.setTicket(mJsTicket);
            jt.setExpiresIn(System.currentTimeMillis() + "");
            JSONObject json = JSONObject.fromObject(jt);
            String obj = json.toString();
            fos.write(obj.getBytes());
            fos.close();
        } else {
            FileInputStream fis = new FileInputStream(file);
            byte[] b = new byte[2048];
            int len = fis.read(b);
            String mJsonJsTicket = new String(b, 0, len);// 读取到的文件内容
            JSONObject object = new JSONObject().fromObject(mJsonJsTicket);
            JsTicket jsTicket = (JsTicket) JSONObject.toBean(object, JsTicket.class);
            if (jsTicket.getExpiresIn() != null) {
                long saveTime = Long.parseLong(jsTicket.getExpiresIn());
                long nowTime = System.currentTimeMillis();
                long remianTime = nowTime - saveTime;
                // System.out.println(TAG + "时间差：" + remianTime);
                if (remianTime < MAX_TIME) {
                    JSONObject o = new JSONObject().fromObject(mJsonJsTicket);
                    JsTicket at = (JsTicket) JSONObject.toBean(o, JsTicket.class);
                    mJsTicket = at.getTicket();
                } else {
                    mJsTicket = getJsTicket().getTicket();
                    FileOutputStream fos = new FileOutputStream(file, false);// 不允许追加
                    JsTicket at = new JsTicket();
                    at.setTicket(mJsTicket);
                    at.setExpiresIn(System.currentTimeMillis() + "");
                    JSONObject json = JSONObject.fromObject(at);
                    String obj = json.toString();
                    fos.write((obj).getBytes());
                    fos.close();
                }

            }
        }
        return mJsTicket;
    }

    public static JsTicket getJsTicket() throws Exception {
        // TODO Auto-generated method stub
        JsTicket jsTicket = new JsTicket();
        String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + getSavedAccess_token()
                + "&type=jsapi";
        JSONObject jsonObject = doGetStr(url);// 使用刚刚写的doGet方法接收结果
        if (jsonObject != null) { // 如果返回不为空，将返回结果封装进JsTicket实体类
            jsTicket.setTicket(jsonObject.getString("ticket"));// 取出ticket
            jsTicket.setExpiresIn(jsonObject.getString("expires_in"));// 取出ticket的有效期
        }
        return jsTicket;
    }


    // 发起get请求的方法。
    public static String GET(String url) {
        String result = "";
        BufferedReader in = null;
        InputStream is = null;
        InputStreamReader isr = null;
        try {
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();
            conn.connect();
            Map<String, List<String>> map = conn.getHeaderFields();
            is = conn.getInputStream();
            isr = new InputStreamReader(is);
            in = new BufferedReader(isr);
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            // 异常记录
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (is != null) {
                    is.close();
                }
                if (isr != null) {
                    isr.close();
                }
            } catch (Exception e2) {
                // 异常记录
            }
        }
        return result;
    }

}
